// app/model/contract_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM } = app.Sequelize;

  const ContractModel = app.model.define('contract', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    contractNumber: {
      type: STRING(50),
      allowNull: false,
      unique: true,
      field: 'contractNumber',
      comment: '合同编号'
    },
    supplierId: {
      type: INTEGER,
      allowNull: false,
      field: 'supplierId',
      comment: '供应商ID'
    },
    contractName: {
      type: STRING(200),
      allowNull: false,
      field: 'contractName',
      comment: '合同名称'
    },
    contractType: {
      type: ENUM('purchase', 'service', 'other'),
      defaultValue: 'purchase',
      field: 'contractType',
      comment: '合同类型: purchase(采购合同), service(服务合同), other(其他)'
    },
    startDate: {
      type: DATE,
      allowNull: false,
      field: 'startDate',
      comment: '合同开始日期'
    },
    endDate: {
      type: DATE,
      allowNull: false,
      field: 'endDate',
      comment: '合同结束日期'
    },
    amount: {
      type: DECIMAL(15, 2),
      allowNull: false,
      field: 'amount',
      comment: '合同金额'
    },
    status: {
      type: ENUM('active', 'expired', 'terminated'),
      defaultValue: 'active',
      field: 'status',
      comment: '合同状态: active(生效中), expired(已过期), terminated(已终止)'
    },
    attachment: {
      type: STRING(500),
      allowNull: true,
      field: 'attachment',
      comment: '合同附件路径'
    },
    remark: {
      type: TEXT,
      allowNull: true,
      field: 'remark',
      comment: '备注'
    },
    createdAt: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      field: 'createdAt',
      comment: '创建时间'
    },
    updatedAt: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      field: 'updatedAt',
      comment: '更新时间'
    }
  }, {
    tableName: 'contracts',
    timestamps: true,
    createdAt: 'createdAt',
    updatedAt: 'updatedAt'
  });

  // 关联关系
  ContractModel.associate = function() {
    app.model.ContractModel.belongsTo(app.model.SupplierModel, {
      as: 'supplier',
      foreignKey: 'supplierId'
    });
  };

  return ContractModel;
};